<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
      }
      div {
        width: 300px;
        margin: 0 auto;
        margin-bottom: 20px;
      }
      label {
        display: inline-block;
        width: 80px;
      }
      input {
        width: calc(100% - 93px);
      }
      button {
        width: 100%;
        height: 30px;
      }
    </style>
  </head>
  <body>
    <!-- 第一步：布局 -->
    <form action="" id="form">
      <div>
        <label for="username">用户名：</label>
        <input
          type="text"
          id="username"
          name="username"
          placeholder="请输入用户名"
        />
      </div>
      <div>
        <label for="password">密码：</label>
        <input
          type="text"
          id="password"
          name="password"
          placeholder="请输入密码"
          type="password"
        />
      </div>
      <div>
        <button>登录</button>
      </div>
    </form>
    <script src="Ajax.js"></script>
    <script>
      window.onload = function () {
        var str = document.cookie;
        var arr = str.split("=");
        console.log(arr, arr[0], arr[1]);
        if (arr.length >= 2 && arr[1] == "1") {
          location.href = "home.html";
        }
      };
      // 第二步：处理form表单的提交事件
      document.getElementById("form").addEventListener("submit", function (e) {
        e.preventDefault(); // 禁止自身本来的事件
        const formData = Object.fromEntries(new FormData(this)); // 1、拿到form提交的信息
        // 2、处理输入校验
        if (!/^[\u4e00-\u9fa5A-Za-z0-9]+$/.test(formData.name)) {
          alert("用户名只能输入中文、英文、数字或他们的组合");
        } else if (!/^[a-zA-z]\w{5,9}$/.test(formData.psd)) {
          alert("密码必须以英文开头，长度为6-10位");
        } else {
          // 3、ajax请求
          Ajax({
            type: "post",
            url: "https://mock.mengxuegu.com/mock/6893730620db2a705aaa2d1a/test/login",
            data: formData,
            success: (data) => {
              let res = JSON.parse(data);
              console.log(res);
              const { code, msg } = res; // 拿到对象中key对应的value值
              if (code == 0) {
                var date = new Date(); //获取当前时间
                date.setDate(date.getDate() + 1); //当前时 + 有效时
                document.cookie = "isLogin=1;expires=" + date; //有有效期，存储大小较小4k
                localStorage.setItem("username", formData.name);
                location.href = "home.html";
              } else {
                alert(`登录失败，${msg}`);
              }
            },
            error: (e) => {
              console.log(e);
            },
          });
        }
      });
    </script>
  </body>
</html>
